﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using AIPASoft.Interfaces;
using AIPASoft.Interfaces.BusinessDomain;

namespace AIPASoftApplicationManager
{
    public class PluginHelper
    {
        private List<string> PluginFiles { get; set; }
        public List<Assembly> Plugins { get; private set; }
        public List<IBusinessDomain> BusinessDomains { get; set; }
        public IApplicationManager ApplicationManager { get; set; }

        public PluginHelper(IApplicationManager applicationManager)
        {
            ApplicationManager = applicationManager;
            PluginFiles = new List<string>();
            Plugins = new List<Assembly>();
            BusinessDomains = new List<IBusinessDomain>();
            PluginFiles = GetPluginFiles();
            //LoadAssembiles();
            LoadBusinessDomains();
        }

        private static List<string> GetPluginFiles()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;
            var pluginFiles = Directory.GetFiles(path, "*.dll").ToList();
            return pluginFiles;
        }

        private void LoadAssembiles()
        {
            foreach (var plugin in PluginFiles)
            {  
                try
                {
                    var ass = Assembly.LoadFrom(plugin);
                    if (ass != null)
                    {
                        foreach (var mytype in ass.GetTypes().Where(mytype => mytype.GetInterfaces().Contains(typeof(IPlugin))))
                        {
                            Console.WriteLine("----> " + mytype);
                            Plugins.Add(ass);
                        } 
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                } 
            }
        }

        private void LoadBusinessDomains()
        {
            foreach (var plugin in PluginFiles)
            {
                try
                {
                    var ass = Assembly.LoadFrom(plugin);
                    if (ass != null)
                    {
                        foreach (Type mytype in ass.GetTypes().Where(mytype => mytype.GetInterfaces().Contains(typeof(IBusinessDomain))))
                        {
                            Console.WriteLine("----> " + mytype);
                            var businessDomain = (IBusinessDomain)Activator.CreateInstance(mytype);
                            businessDomain.ApplicationManager = ApplicationManager;
                            BusinessDomains.Add(businessDomain);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }
}
